<?php

namespace App\Http\Controllers\WeChatService;

use App\Models\InterestRecord;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\common\LMReturn;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\app\user\UserController;
use Illuminate\Support\Facades\Redis;

class WeChatServiceController extends Controller
{
    // 接收微信消息和事件的接口
    public function WeChatNotify(Request $request) {
        $all = $request->all();
        $post_data = file_get_contents("php://input");
        $echostr = $all['echostr'] ?? '';
        $signature = $all["signature"];
        $timestamp = $all["timestamp"];
        $nonce = $all["nonce"];
        $token = WeChatConfig::Token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            $post_data = str_replace('<![CDATA[', '', $post_data);
            $post_data = str_replace(']]>', '', $post_data);
            $post_dic = json_decode(json_encode(simplexml_load_string($post_data)), true);
            $msgType = $post_dic['MsgType'];
            $openID = $post_dic['FromUserName'];
            if ($msgType == 'event') {
                $event = $post_dic['Event'];
                if ($event == 'CLICK') {
                    $key = $post_dic['EventKey'];
                    if ($key == 'key_1') {
                        $res = self::ReceiveMessage($openID);
                    } elseif ($key == 'key_2') {
                        $res = self::CancelReceiveMessage($openID);
                    } elseif ($key == 'key_3') {
                        $res = self::CheckOrders($openID);
                    }
                }
//                elseif ($event == 'subscribe') {
//                    $res = self::FocusPublic($openID);
//                } elseif ($event == 'unsubscribe') {
//                    $res = self::CancelFocusPublic($openID);
//                }
            }
            return $echostr;
        }else{
            return false;
        }
    }

    // 接收click点击事件公众号接收消息
    public static function ReceiveMessage($openID) {
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $data = WeChatServiceSDK::GetUserMessage($access_token, $openID);
            $unionid = $data['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if ($user) {
                User::where('id_number', $user->id_number)
                    ->where('id_type', $user->id_type)
                    ->update(["is_receive"=>1, "public_open_id"=>$data['openid']]);
                $postData = WeChatServiceUtils::CreateModelMessage($openID, '5');
            } else {
                $postData = WeChatServiceUtils::CreateModelMessage($openID, '6');
            }
            $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
            return WeChatServiceSDK::post($postData, $postUrl);
        }
        return true;
    }

    // 接收click点击事件公众号取消接收消息
    public static function CancelReceiveMessage($openID) {
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $data = WeChatServiceSDK::GetUserMessage($access_token, $openID);
            $unionid = $data['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if ($user) {
                User::where('id_number', $user->id_number)
                    ->where('id_type', $user->id_type)
                    ->update(["is_receive"=>0, "public_open_id"=>$data['openid']]);
                $postData = WeChatServiceUtils::CreateModelMessage($openID, '4');
            } else {
                $postData = WeChatServiceUtils::CreateModelMessage($openID, '6');
            }
            $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
            return WeChatServiceSDK::post($postData, $postUrl);
        }
        return true;
    }

    // 接收click点击事件在公众号查看订单状态
    public static function CheckOrders($openID) {
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $data = WeChatServiceSDK::GetUserMessage($access_token, $openID);
            $unionid = $data['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if ($user) {
                if ($user->id_number) {
                    $user_list = User::where('id_number', $user->id_number)
                        ->where('id_type', $user->id_type)
                        ->get();
                    $user_id_list = [];
                    foreach ($user_list as $user_c) {
                        $user_id_list[] = $user_c->id;
                    }
                } else {
                    $user_id_list = [$user->id];
                }
                // 当前在途的本金和利息
                $sum_money = Order::whereIn('user_id', $user_id_list)
                    ->whereIn('order_status', [3, 4])
                    ->first(
                        array(
                            DB::raw('SUM(order_money) as money'),
                            // DB::raw('SUM(interest) as zt_interest')
                        )
                    )->toArray();
                // 预期收益
                $sum_data = InterestRecord::where('is_exit', '2')
                    ->whereHas('order.user', function ($query) use ($user_id_list) {
                        $query->whereIn('id', $user_id_list);
                    })
                    ->whereIn('status', [1, 2])
                    ->first(
                        array(
                            DB::raw('SUM(interest) as zt_interest')
                        )
                    )->toArray();
                // 累计收益
                $sum_interest = InterestRecord::where('is_exit', '2')
                    ->whereHas('order.user', function ($query) use ($user_id_list) {
                        $query->whereIn('id', $user_id_list);
                    })
                    ->whereIn('status', [3])
                    ->first(
                        array(
                            DB::raw('SUM(interest) as history_interest'),
                        )
                    )->toArray();
                $all_orders = Order::whereIn('user_id', $user_id_list)->count();
                $audit_orders = Order::whereIn('user_id', $user_id_list)->where('order_status', 2)->count();
                $earning_orders = Order::whereIn('user_id', $user_id_list)->where('order_status', 4)->count();
                $complete_orders = Order::whereIn('user_id', $user_id_list)->whereIn('order_status', [6, 7, 8])->count();
                $money = UserController::DealMoney($sum_money['money'], '4', '1');
                $earnMoney = UserController::DealMoney($sum_data['zt_interest'], '4', '1');
                $cumulative = UserController::DealMoney($sum_interest['history_interest'], '4', '1');
            }
            $model_data = [
                "count"=>[
                    "value"=>$all_orders ?? 0,
                    "color"=>"#173177"
                ],
                "audit"=>[
                    "value"=>$audit_orders ?? 0,
                    "color"=>"#173177"
                ],
                "earnings"=>[
                    "value"=>$earning_orders ?? 0,
                    "color"=>"#173177"
                ],
                "complete"=>[
                    "value"=>$complete_orders ?? 0,
                    "color"=>"#173177"
                ],
                "money"=>[
                    "value"=>$money ?? 0,
                    "color"=>"#173177"
                ],
                "earnMoney"=>[
                    "value"=>$earnMoney ?? 0,
                    "color"=>"#173177"
                ],
                "cumulative"=>[
                    "value"=>$cumulative ?? 0,
                    "color"=>"#173177"
                ]
            ];
            $postData = WeChatServiceUtils::CreateModelMessage($openID, '3', $model_data);
            $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
            WeChatServiceSDK::post($postData, $postUrl);
        }
        return true;
    }

    // 用户关注公众号操作
    public static function FocusPublic($openID) {
        $postData = WeChatServiceUtils::CreateModelMessage($openID, '2');
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $data = WeChatServiceSDK::GetUserMessage($access_token, $openID);
            $unionid = $data['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if ($user) {
                User::where('id_number', $user->id_number)
                    ->where('id_type', $user->id_type)
                    ->update(["public_open_id"=>$data['openid']]);
            }
            $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
            WeChatServiceSDK::post($postData, $postUrl);
        }
        return true;
    }

    // 用户取消关注公众号操作
    public static function CancelFocusPublic($openID) {
        $access_token = WeChatServiceSDK::GetAccessTokenFromRedis();
        if ($access_token) {
            $data = WeChatServiceSDK::GetUserMessage($access_token, $openID);
            $unionid = $data['unionid'];
            $user = User::where('unionid', $unionid)->first();
            if ($user) {
                User::where('id_number', $user->id_number)
                    ->where('id_type', $user->id_type)
                    ->update(["public_open_id"=>null, "is_receive"=>0]);
            }
        }
        return true;
    }

    // 从小程序绑定微信公共平台UnionID
    public function BindingUnionID(Request $request) {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm('user'), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $user_id = $tokenInfo['user_id'];
            if (isset($all['js_code'])) {
                $getUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=".WeChatConfig::xcxAppID."&secret=".WeChatConfig::xcxAppSecret."&js_code=".$all['js_code']."&grant_type=authorization_code";
                $user_xcx = json_decode(file_get_contents($getUrl), true);
                if (isset($user_xcx['errcode'])) {
                    return ['code'=>300, 'msg'=>'获取openID出错', 'data'=>$user_xcx];
                }
                $openID = $user_xcx['openid'];
                $unionID = $user_xcx['unionid'];
                $user = User::find($user_id);
                User::where('id_number', $user->id_number)
                    ->where('id_type', $user->id_type)
                    ->update(['unionid'=>$unionID, 'xcx_open_id'=>$openID]);
                return LMReturn::Success(['openID'=>$openID, 'unionID'=>$unionID]);
            } else {
                return LMReturn::Error('未传入js_code');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('请重试');
        }
    }


    // 测试接口
    public function CeShi(Request $request) {
//        return Redis::get('accessToken');
        $openID = 'oKdY85qdk9A1Rysejpxa-N_aco6o';
        self::CheckOrders($openID);
    }


}
